import React from 'react'
import Admin from "../../../layout/Admin"
import {DatePicker, PageHeader, Row, Col, Radio, Divider, Button, Table, Card, Modal} from 'antd'
import UserModel from "../../../model/user";
import moment from "moment";
import ActivitySummary from "../../../component/ActivitySummary/ActivitySummary";
const { RangePicker } = DatePicker

export const dayDiff = 3
export const defaultStart = moment().subtract(3, 'day').set({hour:0,minute:0,second:0,millisecond:0})
export const defaultEnd = moment()
export const defaultDateString = 'YYYY-MM-DD HH:mm:ss'
export const mb16 = {
    marginBottom: '16px',
}

class UserTotal extends React.Component {
    constructor(props) {
        super(props)
        this.model = new UserModel()
        this.state = {
            now: moment(),
            today: moment().set({hour:23,minute:59,second:59,millisecond:59}),
            oneWeek: moment().set({hour:23,minute:59,second:59,millisecond:59}).subtract(7, 'day'),
            yesterdayEnd: moment().set({hour:0,minute:0,second:0,millisecond:0}),
            yesterdayStart: moment().subtract(1, 'day').set({hour:0,minute:0,second:0,millisecond:0}),
            zongshu: 0,
            zuori: 0,
            zhouLogin: 0,
            visit: 0,
            zuoriLogin: 0,
            zhouPinglun: 0,
            online: 0,
            onlineVip: 0,
            total: 0,
            昨日激活: 0,
            昨日激活详情: [],
            type: 'reg',
            dayDiff: dayDiff,
            start: defaultStart,
            end: defaultEnd,
            startString: defaultStart.format('YYYY-MM-DD HH:mm:ss'),
            endString: defaultEnd.format('YYYY-MM-DD HH:mm:ss'),
            zhuanfa: 0,
            xinwen: 0,
            shiping: 0,
            liaotian: [],
            liaotianFlag: 1,
            behavior: [],
            yqm: [],
            behaviorStart: moment().set({hour:0,minute:0,second:0,millisecond:0}),
            behaviorEnd: moment(),
            yqmStart: moment().set({hour:0,minute:0,second:0,millisecond:0}),
            yqmEnd: moment(),
            activeDetail: {},
            modal: {
                激活: false,
                activeDetail: false,
            }
        }
    }

    componentDidMount() {
        this.zongshu()
        this.zuori()
        this.visit()
        this.zhouLogin()
        this.zuoriLogin()
        this.zhouPinglun()
        this.online()
        this.onlineVip()
        this.get()
        this.activity()
        this.liaotian()
        this.behavior()
        this.yqm()
        this.昨日激活()
    }

    formatTime = (moment) => {
        return parseInt(moment.format('X'))
    }

    zongshu = () => {
        this.model
            .zongshu()
            .then(res => {
                this.setState({
                    zongshu: res.data.ok,
                })
            })
    }

    zuori = () => {
        this.model
            .reg({
                start: this.state.yesterdayStart.format(defaultDateString),
                end: this.state.yesterdayEnd.format(defaultDateString),
            })
            .then(resp => {
                this.setState({
                    zuori: resp.data.ok,
                })
            })
    }

    visit = () => {
        console.log('昨日登入用户')
        const end = this.state.yesterdayEnd.format(defaultDateString)
        const start = this.state.yesterdayStart.format(defaultDateString)
        console.log(end, start)
        this.model
            .visit({
                end,
                start,
            })
            .then(resp => {
                console.log(resp.data.ok)
                this.setState({
                    visit: resp.data.ok,
                })
            })
    }

    zuoriLogin = () => {

        this.model
            .login({
                end: this.state.yesterdayEnd.format(defaultDateString),
                start: this.state.yesterdayStart.format(defaultDateString),
            })
            .then(resp => {
                this.setState({
                    zuoriLogin: resp.data.ok,
                })
            })
    }

    zhouLogin = () => {
        console.log('zhouLogin')
        const start = this.state.oneWeek.format(defaultDateString)
        const end = this.state.today.format(defaultDateString)
        this.model
            .login({
                end,
                start,
            })
            .then(resp => {
                this.setState({
                    zhouLogin: resp.data.ok,
                })
            })
    }

    zhouPinglun = () => {
        this.model
            .pinglun({
                end: this.state.today.format(defaultDateString),
                start: this.state.oneWeek.format(defaultDateString),
            })
            .then(resp => {
                this.setState({
                    zhouPinglun: resp.data.ok,
                })
            })
    }

    online = () => {
        this.model
            .online()
            .then(resp => {
                this.setState({
                    online: resp.data.ok,
                })
            })
    }

    onlineVip = () => {
        this.model
            .onlineVip()
            .then(resp => {
                this.setState({
                    onlineVip: resp.data.ok,
                })
            })
    }

    get = () => {
        const start = this.state.startString
        const end = this.state.endString
        const type = this.state.type
        this.model[type]({start, end,}).then(resp => {
            const total = resp.data.ok
            this.setState({total})
        })
    }

    activity = () => {
        this.model
            .activity({
                starttime: this.formatTime(this.state.start),
                endtime: this.formatTime(this.state.end),
            })
            .then(values => {

                const [zhuanfa, xinwen, shiping,] = values
                this.setState({
                    zhuanfa,
                    xinwen,
                    shiping,
                })
            })
    }

    liaotian = () => {
        this.model
            .liaotian({
                starttime: this.formatTime(this.state.start),
                endtime: this.formatTime(this.state.end),
                Flag: this.state.liaotianFlag,
            })
            .then((res) => {
                const liaotian = [...res.data.ok]
                this.setState({
                    liaotian,
                })
            })
    }

    callModal = (key) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: true,
            }
        })
    }

    onModalCancel = (key) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: false,
            }
        })
    }

    onRatioChange = (e) => {
        const v = e.target.value
        const stateType = this.state.type
        if (stateType === v) return
        this.setState({
            p: 0,
            type: v,
        }, () => this.get())
    }

    onDateChange = (value, dateString) => {
        const [start, end,] = value
        const [startString, endString,] = dateString
        const dayDiff = end.diff(start, 'day')
        this.setState({
            start,
            end,
            startString,
            endString,
            dayDiff,
        }, () => {
            this.get()
            this.activity()
            this.liaotian()
        })
    }

    onBehaviorDateChange = (value,) => {
        const [start, end,] = value
        this.setState({
            behaviorStart: start,
            behaviorEnd: end,
        }, () => {
            this.behavior()
        })
    }

    onYqmDateChange = (value,) => {
        const [start, end,] = value
        this.setState({
            yqmStart: start,
            yqmEnd: end,
        }, () => {
            this.yqm()
        })
    }

    submit = () => {
        const {start, end, type} = this.state
        this.get({start, end, type})
    }

    behavior = () => {
        const start = this.state.behaviorStart
        const end = this.state.behaviorEnd
        this.model
            .behavior({
                start: this.formatTime(start),
                end: this.formatTime(end),
            })
            .then(resp => {
                if (resp.data.ok) {
                    this.setState({
                        behavior: resp.data.ok,
                    })
                }
            })
    }

    yqm = () => {
        const starttime = this.formatTime(this.state.yqmStart)
        const endtime = this.formatTime(this.state.yqmEnd)
        this.model
            .yqm({
                starttime,
                endtime,
            })
            .then((res) => {
                if (res.data.ok) {
                    this.setState({
                        yqm: res.data.ok,
                    })
                }
            })
    }

    昨日激活 = () => {
        const date = moment(new Date()).subtract(1, 'day').format('YYYYMMDD')
        this.model
            .激活({
                Date: date,
            })
            .then(resp => {
                if (resp.data.ok) {
                    let array = resp.data.ok
                    // array = [{Count: 1,}, {Count: 2,}]
                    const total = array.reduce((current, item) => (item.Count + current), 0)
                    this.setState({
                        昨日激活: total,
                        昨日激活详情: array,
                    })
                }
            })
    }

    onJiHuoDetailClick = () => {
        this.callModal('激活')
    }

    render() {

        const header = <div style={{background: '#fff'}}>
            <PageHeader title='用户统计'/>
        </div>
        const hitHeader = <div style={{background: '#fff'}}>
            <PageHeader title='聊天统计'/>
        </div>
        const behaviorHeader = <div style={{background: '#fff'}}>
            <PageHeader title='用户行为'/>
        </div>
        const yqmHeader = <div style={{background: '#fff'}}>
            <PageHeader title='邀请码填写情况'/>
            <p>总数：{this.state.yqm.length}</p>
        </div>

        const summary = <div>
            <ActivitySummary
                activity={{
                    zongshu: this.state.zongshu,
                    zuori: this.state.zuori,
                    昨日激活用户数: {
                        value: this.state.昨日激活,
                        render: (value) => {
                            return <div>
                                <p style={{display: 'inline-block', marginRight: '16px',}}>{value}</p>
                                <a onClick={this.onJiHuoDetailClick} style={{color: '#333',}}>查看详情</a>
                            </div>
                        },},
                    visit: this.state.visit,
                    zuoriLogin: this.state.zuoriLogin,
                    zhouLogin: this.state.zhouLogin,
                    zhouPinglun: this.state.zhouPinglun,
                    online: this.state.online,
                    onlineVip: this.state.onlineVip,
                }}
            />
        </div>

        const main = <div>
            <Radio.Group
                value={this.state.liaotianFlag}
                defaultChecked={this.state.liaotianFlag}
                onChange={(e) => {
                    this.setState({
                        liaotianFlag: e.target.value,
                    }, () => this.liaotian())
                }}
            >
                <Radio value={1}>足球</Radio>
                <Radio value={2}>篮球</Radio>
                <Radio value={3}>聊天室</Radio>
            </Radio.Group>

            <Row style={mb16}>
                <Col span={6}>
                    <span>选中共 {this.state.dayDiff} 日：</span>
                </Col>
                <Col span={18}>
                    <RangePicker
                        showTime={{ format: 'HH:mm:ss' }}
                        format="YYYY-MM-DD HH:mm:ss"
                        onChange={this.onDateChange}
                        defaultValue={[
                            this.state.start,
                            this.state.end,
                        ]}
                    />
                </Col>
            </Row>


            <ActivitySummary
                activity={{
                    liaotian: this.state.liaotian,
                }}
                liaotianFlag={this.state.liaotianFlag - 1}
            />

        </div>

        const behaviorStart = this.state.behaviorStart
        const behaviorEnd = this.state.behaviorEnd
        const yqmStart = this.state.yqmStart
        const yqmEnd = this.state.yqmEnd

        const behaviorDateDiff = behaviorEnd.diff(behaviorStart, 'day')
        const yqmDateDiff = yqmEnd.diff(yqmStart, 'day')
        const tabs = ['比赛', '视频', '任务', '新闻', '我的', 'ios点击比赛', 'ios点击视频', 'ios点击任务', 'ios点击新闻', 'ios点击我的']
        const behaviorData = this.state.behavior
        const tabsBehaviorData = {}
        const secondBehaviorData = {}

        Object.entries(behaviorData).map((data) => {
            let [key, value,] = data
            if (tabs.includes(key)) {
                tabsBehaviorData[key] = value
            } else {
                secondBehaviorData[key] = value
            }
        })

        // console.log('secondBehaviorData', secondBehaviorData)
        const secondBehaviorDataWithDetail = {}
        const valueKeys = ['点击比赛', '篮球', '足球', '全部', '进行中', '赛程', '赛果', '关注', '筛选', '比赛动画', '比赛视频', '点击视频', '社区', '资讯', '转发']
        const otherKeys = []
        const ks = Object.keys(secondBehaviorData)
        for (let i = 0; i < ks.length; i++) {
            let k = ks[i]

            if (!valueKeys.includes(k)) {
                let isOther = true
                for (let j = 0; j < valueKeys.length; j++) {
                    let valueKey = valueKeys[j]
                    if (k.includes(valueKey)) {
                        isOther = false
                    }
                }
                if (isOther) {
                    otherKeys.push(k)
                }
            }
        }
        valueKeys.map(valueKey => {
            secondBehaviorDataWithDetail[valueKey] = {}
            Object.entries(secondBehaviorData).map(([key, value]) => {
                if (key === '点击篮球比赛' || key === '点击足球比赛' || key === 'ios点击篮球比赛' || key === 'ios点击篮球比赛') {
                    secondBehaviorDataWithDetail['点击比赛'][key] = value
                }
                if (key.includes(valueKey)) {
                    secondBehaviorDataWithDetail[valueKey][key] = value
                }
            })
        })
        otherKeys.map(valueKey => secondBehaviorDataWithDetail[valueKey] = secondBehaviorData[valueKey])

        // console.log('secondBehaviorDataWithDetail', secondBehaviorDataWithDetail)
        // Date: 1600133476
        // Id: 2
        // Myuid: "fc880ff9-ff4b-44e5-b644-c5a0ff8133ac"
        // Uid: "37d67a9c-90f2-485b-9332-a7f3ebfcfa84"
        const columns = [
            {
                // title:
                title: '邀请人ID',
                dataIndex: 'Uid',
            },
            {
                // title:
                title: '被邀请人ID',
                dataIndex: 'Myuid',
            },
            {
                // title:
                title: '填写时间',
                dataIndex: 'Date',
                render: (data) => moment(new Date(data * 1000)).format('YYYY-MM-DD HH:mm:ss'),
            },
        ]
        const behavior = <div>
            {behaviorHeader}
            <Row style={mb16}>
                <Col span={6}>
                    <span>{`${behaviorDateDiff === 0 ? '今' : `近${behaviorDateDiff}`}日用户行为：`}</span>
                </Col>
                <Col span={18}>
                    <RangePicker
                        showTime={{ format: 'HH:mm:ss' }}
                        format="YYYY-MM-DD HH:mm:ss"
                        onChange={this.onBehaviorDateChange}
                        defaultValue={[
                            this.state.behaviorStart,
                            this.state.behaviorEnd,
                        ]}
                    />
                </Col>
            </Row>
            {/*<ActivitySummary*/}
            {/*    activity={this.state.behavior}*/}
            {/*/>*/}
            <div>
                <p>一级菜单点击</p>
                <ActivitySummary activity={tabsBehaviorData}/>
            </div>
            <div>
                <p>二级页面点击</p>
                {Object.entries(secondBehaviorDataWithDetail).map(([key, value,], index) => {
                    const type = Object.prototype.toString.call(value)
                    let result
                    let total
                    const isObject = type === '[object Object]'
                    const isNumber = type === '[object Number]'
                    if (isNumber) {
                        result = <p>{value}</p>
                    }
                    if (isObject) {
                        total = Object.values(value).reduce((a, b) => a + b, 0)
                        result = <div>
                            <p style={{display: 'inline-block', marginRight: '16px',}}>总数：{total}</p>
                            {total > 0 ? <a
                                onClick={() => {
                                    this.setState({
                                        activeDetail: value,
                                    }, () => {
                                        this.callModal('activeDetail')
                                    })
                                }}
                                style={{color: '#333',}}
                            >查看详情</a> : null}
                        </div>
                    }
                    return <Card
                        title={key}
                        key={index}
                        style={{width: '200px', display: 'inline-block', margin: '8px',}}
                    >
                        {result}
                    </Card>
                })}
                {/*<ActivitySummary activity={secondBehaviorData}/>*/}
            </div>

        </div>

        const yqmSummary = <div>
            {yqmHeader}
            <Row style={mb16}>
                <Col span={6}>
                    <span>{`${yqmDateDiff === 0 ? '今' : `近${yqmDateDiff}`}日邀请码填写情况：`}</span>
                </Col>
                <Col span={18}>
                    <RangePicker
                        showTime={{ format: 'HH:mm:ss' }}
                        format="YYYY-MM-DD HH:mm:ss"
                        onChange={this.onYqmDateChange}
                        defaultValue={[
                            this.state.yqmStart,
                            this.state.yqmEnd,
                        ]}
                    />
                </Col>
            </Row>
            <Table
                columns={columns}
                dataSource={this.state.yqm}
            />
        </div>

        const 激活详情data = this.state.昨日激活详情.reduce((current, item) => {
            let title = item.From
            if (title === '') title = '未填写'
            const m = {
                // 'retou': '热投',
                // 'promotion_channel': '渠道包',
                // 'xiaomi': '小米',
                'promotion_channel': '360渠道',
                '360': '360应用市场',
                'retou': '公司渠道',
                'huawei': '华为应用市场',
                'xiaomi': '小米应用市场',
                'vivo': 'vivo应用市场',
                'oppo': 'oppo应用市场',
                'wandoujia': '豌豆荚应用市场',
                'google_tw': '谷歌',
                'kuaishou': '快手',

            }
            if (m[title]) {
                title = m[title]
            }
            current[title] = item.Count
            return current
        }, {})
        const 激活详情弹窗 = <Modal
            visible={this.state.modal.激活}
            onCancel={() => this.onModalCancel('激活')}
            maskClosable
        >
            <ActivitySummary activity={激活详情data}/>
        </Modal>
        const activeDetailModal = <Modal
            visible={this.state.modal.activeDetail}
            onCancel={() => this.onModalCancel('activeDetail')}
            maskClosable
        >
            <ActivitySummary activity={this.state.activeDetail}/>
        </Modal>
        return <>
            {激活详情弹窗}
            {activeDetailModal}
            <Admin>
                <div className='list-container'>
                    {header}
                    {summary}
                    {behavior}
                    {yqmSummary}
                    {hitHeader}
                    {main}
                </div>
            </Admin>
        </>
    }
}


export default UserTotal
